﻿using System.Xml.Schema;
using SWD = System.Web.Services.Description;

namespace MockingBird.Wsdl.Parser
{

    /// <summary>
    /// represents a part of a message
    /// </summary>
    public class OperationMessagePart
    {
        public string Name;
        public string ElementName;
        public XmlSchemaComplexType ElementSchema;
        public string ElementNamespace;

        public OperationMessagePart(SWD.ServiceDescription desc, SWD.MessagePart part)
        {
            Name = part.Name;
            ElementName = part.Element.Name;
            ElementNamespace = part.Element.Namespace.ToString();
            //now we have to find the schema
            ElementSchema = FindElementSchema(desc, ElementName);

        }

        private XmlSchemaComplexType FindElementSchema(SWD.ServiceDescription desc, string elementName)
        {
            //Logic: look through all the elements to find a match and then find the schema Type Name
            //corresponding to the located Element. Then use that name and traverse the complex types
            //collection to find the required complex type
            XmlSchemaComplexType locatedSchema = null;
            foreach (XmlSchema schema in desc.Types.Schemas)
            {
                foreach (XmlSchemaElement el in schema.Elements.Values)
                {
                    if (el.Name.Equals(elementName))
                    {
                        //Get the simple name of the schema type
                        string schemaTypeName = el.SchemaTypeName.Name;
                        locatedSchema = GetComplexType(schema, schemaTypeName);
                        //need to do some error checking here
                        break;
                    }

                }

            }
            return locatedSchema;

        }

        private XmlSchemaComplexType GetComplexType(XmlSchema schema, string typeName)
        {
            XmlSchemaComplexType locatedSchema = null;

            foreach (XmlSchemaType schType in schema.SchemaTypes.Values)
            {
                if ((schType is XmlSchemaComplexType) && (schType.Name.Equals(typeName)))
                {
                    locatedSchema = (XmlSchemaComplexType)schType;
                    break;
                }

            }

            return locatedSchema;

        }



    }

}
